<template>
  <Row justify="space-between" v-if="showTableView"
    :style="{ marginTop: '1px', verticalAlign: 'bottom', display: 'flex' }">
    <Col>
    <Input v-model:value="params.selname" placeholder="名称" :style="{ width: '300px', margin: '0 18px' }"></Input>

    <Tooltip title="上传博客" color="blue">
      <Upload :multiple="true" :show-upload-list="false" :before-upload="handleBeforeUpload" class="upload-list-inline">
        <Button style="margin: 0 8px" shape="circle" :icon="h(UploadOutlined)"></Button>
      </Upload>
    </Tooltip>
    <Tooltip title="查询名称" color="blue">
      <Button style="margin: 0 8px" shape="circle" :icon="h(SearchOutlined)" @click="selblogbyname"></Button>
    </Tooltip>
    <Tooltip title="清空" color="blue">
      <Button style="margin: 0 8px" shape="circle" :icon="h(ClearOutlined)" @click="clearname"></Button>
    </Tooltip>
    <Tooltip title="创建目录" color="blue">
      <Button style="margin: 0 8px" shape="circle" :icon="h(FolderAddOutlined)" @click="addFile"></Button>
    </Tooltip>
    <Tooltip title="创建博客" color="blue">
      <Button style="margin: 0 8px" shape="circle" :icon="h(FileAddOutlined)" @click="addBlog"></Button>
    </Tooltip>
    </Col>
    <Col>
    <Breadcrumb :style="{
      textAlign: 'right',
      margin: '0 18px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'flex-end',
    }">
      <BreadcrumbItem>
        <a href="#" @click.prevent="jump('')">根目录</a>
      </BreadcrumbItem>
      <BreadcrumbItem v-for="(part, index) in urls" :key="part">
        <a href="#" @click.prevent="jumpurl(index)">{{ part }}</a>
      </BreadcrumbItem>
    </Breadcrumb>
    </Col>
  </Row>
  <Table v-if="showTableView" bordered :data-source="tabledata" :columns="columns" style="margin-top: 1px">
    <template #bodyCell="{ column, text, record }">
      <template v-if="column.dataIndex === 'name'">
        <div class="editable-cell">
          <div v-if="editableData[record.index]" class="editable-cell-input-wrapper">
            <Input v-model:value="editableData[record.index].name" @pressEnter="save(record)" />
            <close-outlined class="editable-cell-icon-close" @click="cancel(record.index)" />
            <check-outlined class="editable-cell-icon-check" @click="save(record)" />
          </div>
          <div v-else class="editable-cell-text-wrapper">
            {{ text || " " }}
            <edit-outlined class="editable-cell-icon" @click="edit(record)" />
          </div>
        </div>
      </template>

      <template v-else-if="column.dataIndex === 'operation'">
        <Tag color="green" @click="handleView(record)">查看</Tag>
        <Divider type="vertical" />
        <Tag color="orange" @click="handleEdit(record)">编辑</Tag>
        <Divider type="vertical" />
        <Popconfirm v-if="tabledata.length" title="确定删除?" @confirm="handleDelete(record)">
          <Tag color="red">删除</Tag>
        </Popconfirm>
      </template>
    </template>
  </Table>

  <div v-if="showBlogView" class="mt-0">
    <Card title="Markdown">
      <template #extra><Button type="primary" @click="back"> 返回 </Button></template>
      <v-md-preview :text="valueRef"></v-md-preview>
    </Card>
  </div>
  <div v-if="showEditBlogView" class="mt-0">
    <Card title="Markdown Edit...">
      <template #extra>
        <Button type="primary" @click="back"> 返回 </Button>
        <Button type="primary" @click="saveBlog" class="ml-2"> 保存 </Button>
      </template>
      <v-md-editor v-model="valueRef" height="750px" :include-level="[3, 4]" :disabled-menus="[]"
        @upload-image="handleUploadImage" @save="saveBlogData"></v-md-editor>
    </Card>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onBeforeMount, h } from "vue";
import type { UnwrapRef } from "vue";
import {
  SearchOutlined,
  CheckOutlined,
  EditOutlined,
  CloseOutlined,
  ClearOutlined,
  FileAddOutlined,
  FolderAddOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import {
  Table,
  Input,
  Popconfirm,
  Button,
  Tag,
  message,
  Divider,
  Row,
  Breadcrumb,
  BreadcrumbItem,
  Col,
  Card,
  Tooltip,
  Upload,
} from "ant-design-vue";
import { post, upload } from "../util/MyAxios";
import { Api } from "../util/Api";
const params = ref({
  path: "",
  keypath: "",
  name: "",
  oldname: "",
  newname: "",
  content: "",
  selname: "",
  currentPage: 1,
  pageSize: 99999999,
});
const tabledata = ref<any>();
const valueRef = ref(``);
const showTableView = ref(true);
const showBlogView = ref(false);
const showEditBlogView = ref(false);
const urls = ref<string[]>([]);

const columns = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    width: "30%",
  },
  {
    title: "类型",
    dataIndex: "remark",
    key: "remark",
    width: "20%",
  },
  {
    title: "创建时间",
    dataIndex: "ctime",
    key: "ctime",
    width: "15%",
  },
  {
    title: "更新时间",
    dataIndex: "utime",
    key: "utime",
    width: "15%",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    width: "20%",
  },
];

const editableData: UnwrapRef<Record<number, any>> = reactive({});

const edit = (key: any) => {
  editableData[key.index] = JSON.parse(
    JSON.stringify(
      tabledata.value.filter((item) => key.index === item.index)[0]
    )
  );
};
const save = (key: any) => {
  params.value.oldname = key.name;
  params.value.newname = editableData[key.index].name;
  if (key.isfolder) {
    editBlogDirNamePost();
  } else {
    editBlogNamePost();
  }
  delete editableData[key.index];
};

const cancel = (key: number) => {
  delete editableData[key];
};

//页面初加载
onBeforeMount(() => {
  fetchData();
});

const handleBeforeUpload = (file) => {
  const formData = new FormData();
  formData.append("file", file);
  if (params.value.path) {
    formData.append("fileurl", params.value.path);
  }
  return upload(Api.Blog_UploadBlog, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  })
    .then((response) => {
      message.info("已上传:" + response.data);
      fetchData();
      return false;
    })
    .catch((error) => {
      console.error(error);
      return false;
    });
};

//刷新表格数据
async function fetchData() {
  await post(Api.Blog_GetBlogPathInfo, params.value)
    .then((response) => {
      if (response.data && response.data.rows.length > 0) {
        for (let i = 0; i < response.data.rows.length; i++) {
          if (!response.data.rows[i].isfolder) {
            response.data.rows[i].remark = getSize(response.data.rows[i].length);
          } else {
            response.data.rows[i].remark = "文件目录";
          }
        }
      }
      tabledata.value = response.data.rows;
    })
    .catch((error) => {
      console.error(error);
    });
}

//查询博客通过名称
async function selblogbyname() {
  if (params.value.selname && params.value.selname.length > 0) {
    await post(Api.Blog_SelBlogByName, params.value)
      .then((response) => {
        if (response.data && response.data.length > 0) {
          for (let i = 0; i < response.data.length; i++) {
            if (!response.data[i].isfolder) {
              response.data[i].remark = getSize(response.data[i].length);
            } else {
              response.data[i].remark = "文件目录";
            }
          }
        }
        tabledata.value = response.data;
      })
      .catch((error) => {
        console.error(error);
      });
  } else {
    fetchData();
  }
}

//获取文件内容数据
async function getBlogData() {
  await post(Api.Blog_GetBlogData, params.value)
    .then((response) => {
      valueRef.value = response.data;
    })
    .catch((error) => {
      console.error(error);
    });
}
//保存博客内容到服务器
async function saveBlogData() {
  params.value.content = valueRef.value;
  await post(Api.Blog_SaveBlogData, params.value)
    .then((response) => {
      showMessage(response.data, "保存");
    })
    .catch((error) => {
      console.error(error);
    });
  params.value.content = "";
}
//创建一个新博客
async function addBlogPost() {
  await post(Api.Blog_AddBlog, params.value)
    .then((response) => {
      showMessage(response.data, "添加博客");
      fetchData();
    })
    .catch((error) => {
      console.error(error);
    });
}
//删除一个博客
async function delBlogPost() {
  await post(Api.Blog_DelBlog, params.value)
    .then((response) => {
      showMessage(response.data, "删除博客");
      fetchData();
    })
    .catch((error) => {
      console.error(error);
    });
}
//删除一个博客目录
async function delBlogDirPost() {
  await post(Api.Blog_DelBlogDir, params.value)
    .then((response) => {
      showMessage(response.data, "删除博客目录");
      fetchData();
    })
    .catch((error) => {
      console.error(error);
    });
}
//创建一个博客目录
async function addBlogDirPost() {
  await post(Api.Blog_AddBlogDirectory, params.value)
    .then((response) => {
      showMessage(response.data !== "", "添加目录");
      if (response.data !== "") {
        urls.value.push(response.data);
        jumpurl(urls.value.length - 1);
      }
    })
    .catch((error) => {
      console.error(error);
    });
}
//修改博客文件名称
async function editBlogNamePost() {
  await post(Api.Blog_EditBlogDirOrName, params.value)
    .then((response) => {
      showMessage(response.data, "修改文件名称");
      fetchData();
    })
    .catch((error) => {
      console.error(error);
    });
}

//修改博客目录名称
async function editBlogDirNamePost() {
  await post(Api.Blog_EditBlogDirOrName, params.value)
    .then((response) => {
      showMessage(response.data, "修改目录名称");
      fetchData();
    })
    .catch((error) => {
      console.error(error);
    });
}

function showMessage(result, prefix) {
  if (result) {
    message.success({
      content: prefix + "成功",
      duration: 2,
    });
  } else {
    message.error({
      content: prefix + "失败",
      duration: 2,
    });
  }
}
//回到根目录
function jump(url) {
  params.value.path = url;
  urls.value = [];
  fetchData();
}
//回到指定目录
function jumpurl(index) {
  let urlstr = "";
  let t = urls.value.length - 1 - index;
  if (t > 0) {
    for (let i = 0; i < t; i++) {
      urls.value.pop();
    }
  }
  for (let i = 0; i < urls.value.length; i++) {
    if (i <= index) {
      if (urlstr === "") {
        urlstr = urls.value[i];
      } else {
        urlstr = urlstr + "/" + urls.value[i];
      }
    }
  }
  params.value.path = urlstr;
  fetchData();
}
//文件大小格式转换
function getSize(length) {
  if (length === 0) return "0 B";

  const units = ["B", "KB", "MB", "GB", "TB"];
  let index = Math.floor(Math.log(length) / Math.log(1024));
  if (index > units.length - 1) index = units.length - 1;

  const convertedSize = length / Math.pow(1024, index);
  return convertedSize.toFixed(2) + " " + units[index];
}
//返回表格
function back() {
  showBlogView.value = false;
  showTableView.value = true;
  showEditBlogView.value = false;
}
//提交当前内容
function saveBlog() {
  console.log("提交 博客");
  saveBlogData();
}
//创建博客
function addBlog() {
  addBlogPost();
}
//新建目录
function addFile() {
  addBlogDirPost();
}

//点击了删除
function handleDelete(record) {
  if (record.isfolder) {
    params.value.name = record.name;
    delBlogDirPost();
  } else {
    params.value.name = record.name;
    delBlogPost();
  }
}
//点击了查看
function handleView(record) {
  if (record.isfolder) {
    urls.value.push(record.name);
    jumpurl(urls.value.length - 1);
  } else {
    params.value.keypath = record.keypath;
    getBlogData();
    showTableView.value = false;
    showBlogView.value = true;
    showEditBlogView.value = false;
  }
}
//编辑博客
function handleEdit(record) {
  if (record.isfolder) {
    message.success("请编辑博客文件");
    return;
  }
  params.value.keypath = record.keypath;
  getBlogData();
  showTableView.value = false;
  showBlogView.value = false;
  showEditBlogView.value = true;
}
//提交博客图片
function handleUploadImage(event, insertImage, files) {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  if (files && files.length >= 1) {
    const formData = new FormData();
    formData.append("file", files[0]);
    upload(Api.Blog_UploadBlogImg, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
      .then((response) => {
        // showMessage(response.data, '上传图片');
        insertImage({
          url: response.data,
          desc: "",
          // width: 'auto',
          // height: 'auto',
        });
        console.log(response.data);
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

const clearname = () => {
  params.value.selname = "";
};
</script>
<style lang="less" scoped>
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}

.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 48px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 48px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon,
  .editable-cell-icon-close {
    position: absolute;
    right: 24px;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon-close {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-close:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
